package com.zhuyu.downloadlibrary;


import android.app.AlertDialog;
import android.app.Dialog;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ProgressBar;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.DialogFragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;

import java.util.Optional;

public class DownloadDialog extends DialogFragment {
    public static final String EXTRA_TITLE = "title";
    public static final String EXTRA_URL = "url";
    public static final String EXTRA_filepath = "filepath";
    public static final String EXTRA_IS_FORCE = "isForce";

    private ProgressBar progressBar;
    private TextView progress1Tv;
    private TextView progress2Tv;

    DownloadTask downloadTask = null;

    private String filePath;

    public static DownloadDialog newInstance(String url, String filePath, boolean isForceUpdate) {
        DownloadDialog dialog = new DownloadDialog();
        Bundle bundle = new Bundle();
        bundle.putString(EXTRA_URL, url);
        bundle.putString(EXTRA_filepath, filePath);
        bundle.putBoolean(EXTRA_IS_FORCE, isForceUpdate);
        dialog.setArguments(bundle);
        return dialog;
    }

    private String url = "";

    @NonNull
    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {

        View view = LayoutInflater.from(getActivity()).inflate(R.layout.download_dialog_layout, null);
        initView(view);


        if (Optional.ofNullable(getArguments()).isPresent()) {
            url = getArguments().getString(EXTRA_URL);

            boolean forceUpdate = getArguments().getBoolean(EXTRA_IS_FORCE);
            filePath = getArguments().getString(EXTRA_filepath);

            AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(getActivity()).setView(view)
                    .setTitle("正在下载").setCancelable(false)
                    // 对于点击返回键不消失，需要监听OnKeyListener:
                    .setOnKeyListener((d, keyCode, event) -> keyCode == KeyEvent.KEYCODE_BACK);

            if (!forceUpdate) {
                dialogBuilder.setNegativeButton("取消下载", (d, which) -> downloadTask.cancelDownload());
            }

            return dialogBuilder.create();
        } else {
            return super.onCreateDialog(savedInstanceState);
        }
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

        // 点击外部不消失的方法：
        Optional.ofNullable(getDialog()).ifPresent(d -> {
            d.setCanceledOnTouchOutside(false);
            startDownload(url, filePath);
        });
        return super.onCreateView(inflater, container, savedInstanceState);
    }


    private void initView(View view) {
        progressBar = view.findViewById(R.id.dialog_progressBar);
        progress1Tv = view.findViewById(R.id.dialog_progress1Tv);
        progress2Tv = view.findViewById(R.id.dialog_progress2Tv);
    }

    private void startDownload(String downloadUrl, String filepath) {
        if (downloadTask == null) {
            downloadTask = new DownloadTask(getActivity(), filepath, new DownloadListener() {
                @Override
                public void onSuccess() {
                    progressBar.setProgress(100);
                    progress1Tv.setText("100%");
                    progress2Tv.setText("100/100");

                    Optional.ofNullable(getDialog()).ifPresent(Dialog::dismiss);
                    if (mListener != null) {
                        mListener.onSuccess();
                    }
                }

                @Override
                public void onProgress(int progress) {
                    progressBar.setProgress(progress);
                    progress1Tv.setText(progress + "%");
                    progress2Tv.setText(progress + "/100");
                }

                @Override
                public void onFailed() {
                    Optional.ofNullable(getDialog()).ifPresent(Dialog::dismiss);
                    if (mListener != null) {
                        mListener.onError();
                    }
                }

                @Override
                public void onCanceled() {

                }

                @Override
                public void onPaused() {

                }
            });
            // 执行task
            downloadTask.execute(downloadUrl);
        }

    }

    DownloadSimpleListener mListener;

    public interface DownloadSimpleListener {
        void onSuccess();

        void onError();
    }

    public void setDownloadListener(DownloadSimpleListener listener) {
        mListener = listener;
    }


    @Override
    public void show(FragmentManager manager, String tag) {
        FragmentTransaction ft = manager.beginTransaction();
        ft.add(this, tag);
        ft.commitAllowingStateLoss();
    }


    @Override
    public void dismiss() {
        if (getActivity() != null && !getActivity().isFinishing()) {
            super.dismissAllowingStateLoss();
        }
    }


}
